﻿using Kingdee.BOS.App;
using Kingdee.BOS.Collections.Generic;
using Kingdee.BOS.Contracts;
using Kingdee.BOS.Core.CommonFilter;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Core.Report.PlugIn;
using Kingdee.BOS.Core.Report;
using Kingdee.BOS.Core.SqlBuilder;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Orm.Metadata.DataEntity;
using Kingdee.BOS.Resource;
using Kingdee.BOS;
using Kingdee.K3.FIN.App.Core;
using Kingdee.K3.FIN.App.Core.SplitTable;
using Kingdee.K3.FIN.CB.Common.Core.ConstDefine;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Kingdee.K3.FIN.CB.Common.BusinessEntity;

namespace RK.ReportPlugin.Local
{
    public abstract class AbstractCBReportService: AbstratCostReport
    {
        protected string Summation = ResManager.LoadKDString("合计", "003218000008803", (SubSystemType)4, new object[0]);

        private CBInternationalConst _CBInternationalConst;

        private int _CommandTimeOut;

        protected bool IsFirstLoad
        {
            get;
            set;
        }

        protected bool IsDevelopByCustomer
        {
            get;
            set;
        }

        public int LCID => this.Context.UserLocale.LCID;

        public CBInternationalConst CBInternationalConst
        {
            get
            {
                //IL_0009: Unknown result type (might be due to invalid IL or missing references)
                //IL_0013: Expected O, but got Unknown
                if (_CBInternationalConst == null)
                {
                    _CBInternationalConst = (CBInternationalConst)(object)new CBInternationalConst();
                }
                return _CBInternationalConst;
            }
        }

        public int CommandTimeOut
        {
            get
            {
                if (_CommandTimeOut == 0)
                {
                    _CommandTimeOut = CommonFunction.GetCommandTimeOut(1000);
                }
                return _CommandTimeOut;
            }
        }

        protected override List<Tuple<string, bool?>> AddNeedSplitTable()
        {
            List<Tuple<string, bool?>> list = new List<Tuple<string, bool?>>();
            list.Add(new Tuple<string, bool?>("T_CB_PROORDERINFO", true));
            list.Add(new Tuple<string, bool?>("T_CB_PROORDERINFO", false));
            list.Add(new Tuple<string, bool?>("T_CB_CostMatterial", true));
            list.Add(new Tuple<string, bool?>("T_CB_CostMatterial", false));
            list.Add(new Tuple<string, bool?>("T_CB_CostMatterialDetail", true));
            list.Add(new Tuple<string, bool?>("T_CB_CostMatterialDetail", false));
            list.Add(new Tuple<string, bool?>("T_CB_CostCalExpense", true));
            list.Add(new Tuple<string, bool?>("T_CB_CostCalExpense", false));
            list.Add(new Tuple<string, bool?>("T_CB_CostCalExpenseDetail", true));
            list.Add(new Tuple<string, bool?>("T_CB_CostCalExpenseDetail", false));
            return list;
        }

        public override void Initialize()
        {
            //CommonFunction.SetReportPropertyDisableQueryContext(((AbstractSysReportServicePlugIn)this).Context, ((AbstractSysReportServicePlugIn)this).ReportProperty);
            //((AbstratCostReport)this).Initialize();
            base.Initialize();
            IsFirstLoad = true;
            IsDevelopByCustomer = false;
        }

        public virtual void ConvertCustomFilterToCondition(IRptParams filter, AbstractFilterCondition condition)
        {
        }

        protected virtual void ConvertCostCalLinkParamToCustomFilterParam(Dictionary<string, object> openParam, DynamicObject customFilter)
        {
            ((AbstratCostReport)this).AcctgSystemId=((long)Convert.ToInt32(openParam["FAcctgSysId"]));
            customFilter["ACCTGSYSTEMID_Id"]=(object)((AbstratCostReport)this).AcctgSystemId;
            IMetaDataService metaDataService = ServiceFactory.GetMetaDataService(((AbstractSysReportServicePlugIn)this).Context);
            FormMetadata val = (FormMetadata)(object)(FormMetadata)metaDataService.Load(((AbstractSysReportServicePlugIn)this).Context, "Org_AccountSystem", true);
            DynamicObjectType dynamicObjectType = val.BusinessInfo.GetDynamicObjectType();
            DynamicObject val2 = (DynamicObject)(object)new DynamicObject(dynamicObjectType);
            val2["Id"] = (object)((AbstratCostReport)this).AcctgSystemId;
            val2["Name"]= openParam["FAcctgSysName"];
            val2["Number"] = openParam["FAcctgSysNumber"];
            customFilter["ACCTGSYSTEMID"]= (object)val2;
            ((AbstratCostReport)this).AcctgOrgId=((long)Convert.ToInt32(openParam["FAcctgOrgId"]));
            customFilter["ACCTGORGID_Id"]= (object)((AbstratCostReport)this).AcctgOrgId;
            val2 = (DynamicObject)(object)new DynamicObject(dynamicObjectType);
            val2["Id"]= (object)((AbstratCostReport)this).AcctgOrgId;
            val2["Name"] = openParam["FAcctgOrgName"];
            val2["Number"] = openParam["FAcctgOrgNumber"];
            customFilter["ACCTGORGID"] = (object)val2;
            ((AbstratCostReport)this).AcctgOrgId = ((long)Convert.ToInt32(openParam["FAcctPolicyId"]));
            customFilter["ACCTPOLICYID_Id"]= (object)((AbstratCostReport)this).AcctPolicyId;
            val2 = (DynamicObject)(object)new DynamicObject(dynamicObjectType);
            val2["Id"]= (object)((AbstratCostReport)this).AcctPolicyId;
            val2["Name"] = openParam["FAcctPolicyName"];
            val2["Number"] = openParam["FAcctPolicyNumber"];
            customFilter["ACCTPOLICYID"] = (object)val2;
            customFilter["CurrencyID_Id"] = openParam["LocalCurrId"];
            val2 = (DynamicObject)(object)new DynamicObject(dynamicObjectType);
            val2["Id"] = openParam["LocalCurrId"];
            long currencyId = Convert.ToInt64(openParam["LocalCurrId"]);
            string currencyNameById = GetCurrencyNameById(currencyId);
            val2["Name"] = (object)currencyNameById;
            val2["Number"] = (object)"";
            customFilter["CurrencyID"] = (object)val2;
            ((AbstratCostReport)this).Year=((int)Convert.ToInt16(openParam["FYear"]));
            ((AbstratCostReport)this).Period=((int)Convert.ToInt16(openParam["FPeriod"]));
            customFilter["Year"]= (object)((AbstratCostReport)this).Year;
            customFilter["Period"]= (object)((AbstratCostReport)this).Period;
            if (((KeyedCollectionBase<string, DynamicProperty>)(object)customFilter.DynamicObjectType.Properties).ContainsKey("FEndYear"))
            {
                customFilter["FEndYear"] = (object)((AbstratCostReport)this).Year;
                customFilter["FEndPeriod"]= (object)((AbstratCostReport)this).Period;
                ((AbstratCostReport)this).EndYear=(((AbstratCostReport)this).Year);
                ((AbstratCostReport)this).EndPeriod=(((AbstratCostReport)this).Period);
            }
            if (((KeyedCollectionBase<string, DynamicProperty>)(object)customFilter.DynamicObjectType.Properties).ContainsKey("ISSHOWDETAIL"))
            {
                customFilter["ISSHOWDETAIL"]= (object)Convert.ToBoolean(openParam["ISSHOWDETAIL"]);
            }
        }

        public virtual void GenerateDecimalControlField()
        {
        }

        protected virtual void AddCustomParams(IRptParams filter)
        {
            filter.CustomParams.Clear();
        }

        public override void BuilderReportSqlAndTempTable(IRptParams filter, string tableName)
        {
            //IL_00ff: Unknown result type (might be due to invalid IL or missing references)
            long parentAcctgSystemId = 0L;
            long filterAcctgSystemId = 0L;
            bool flag = CheckFilterConditionIsValid(filter, out parentAcctgSystemId, out filterAcctgSystemId);
            if (parentAcctgSystemId > 0 && !IsFirstLoad)
            {
                ((AbstratCostReport)this).BuilderReportSqlAndTempTable(filter, tableName);
            }
            else if (parentAcctgSystemId == 0 || filterAcctgSystemId > 0)
            {
                ((AbstratCostReport)this).BuilderReportSqlAndTempTable(filter, tableName);
            }
            else
            {
                if (!flag || !IsFirstLoad)
                {
                    return;
                }
                Dictionary<string, object> dictionary = new Dictionary<string, object>();
                if (filter.CustomParams.ContainsKey("OpenParameter"))
                {
                    dictionary = (filter.CustomParams["OpenParameter"] as Dictionary<string, object>);
                    if (dictionary != null && dictionary.ContainsKey("FAcctgSysId"))
                    {
                        IsFirstLoad = false;
                        ClearParentCustomFilter(filter);
                        ConvertCostCalLinkParamToCustomFilterParam(dictionary, filter.FilterParameter.CustomFilter);
                        ((AbstratCostReport)this).BuilderReportSqlAndTempTable(filter, tableName);
                    }
                }
                if (!filter.CustomParams.ContainsKey("ParentReportCurrentRow"))
                {
                    return;
                }
                dictionary = (filter.CustomParams["ParentReportCurrentRow"] as Dictionary<string, object>);
                if (dictionary != null && filter.CustomParams.ContainsKey("ParentReportFilter"))
                {
                    DynamicObject customFilter = ((FilterParameter)filter.CustomParams["ParentReportFilter"]).CustomFilter;
                    if (customFilter["AcctgSystemId_Id"] != null)
                    {
                        IsFirstLoad = false;
                        ClearParentCustomFilter(filter);
                        ((AbstratCostReport)this).BuilderReportSqlAndTempTable(filter, tableName);
                    }
                }
            }
        }

        protected virtual bool CheckFilterConditionIsValid(IRptParams filter, out long parentAcctgSystemId, out long filterAcctgSystemId)
        {
            //IL_00d1: Unknown result type (might be due to invalid IL or missing references)
            //IL_016c: Unknown result type (might be due to invalid IL or missing references)
            parentAcctgSystemId = 0L;
            filterAcctgSystemId = 0L;
            Dictionary<string, object> dictionary = new Dictionary<string, object>();
            if (filter != null && filter.CustomParams != null && filter.CustomParams.ContainsKey("OpenParameter"))
            {
                dictionary = (filter.CustomParams["OpenParameter"] as Dictionary<string, object>);
                if (dictionary != null && dictionary.ContainsKey("FAcctgSysId"))
                {
                    parentAcctgSystemId = Convert.ToInt64(dictionary["FAcctgSysId"]);
                    return parentAcctgSystemId > 0;
                }
            }
            if (filter != null && filter.CustomParams != null && filter.CustomParams.ContainsKey("ParentReportCurrentRow"))
            {
                dictionary = (filter.CustomParams["ParentReportCurrentRow"] as Dictionary<string, object>);
                if (dictionary != null && dictionary.Count > 0 && filter.CustomParams.ContainsKey("ParentReportFilter"))
                {
                    DynamicObject customFilter = ((FilterParameter)filter.CustomParams["ParentReportFilter"]).CustomFilter;
                    if (customFilter["AcctgSystemId_Id"] != null)
                    {
                        parentAcctgSystemId = Convert.ToInt64(customFilter["AcctgSystemId_Id"]);
                        return parentAcctgSystemId > 0;
                    }
                }
            }
            if (filter != null && filter.FilterParameter.CustomFilter != null && filter.FilterParameter.CustomFilter["AcctgSystemId_Id"] != null)
            {
                filterAcctgSystemId = Convert.ToInt64(filter.FilterParameter.CustomFilter["AcctgSystemId_Id"]);
            }
            if (parentAcctgSystemId == 0 && filterAcctgSystemId == 0)
            {
                throw new KDBusinessException("CBReport", ResManager.LoadKDString("缺少必要参数，请先在过滤界面中设置参数！", "003217000022320", (SubSystemType)4, new object[0]));
            }
            return true;
        }

        public string GetAcctFilterForBizOrg(AbstractFilterCondition condition)
        {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.AppendLine(" AND EXISTS (select 1 from T_ORG_ACCOUNTSYSTEM acctSys ");
            stringBuilder.AppendLine(" INNER JOIN T_ORG_ACCTSYSENTRY acctOrg on acctOrg.FACCTSYSTEMID=acctSys.FACCTSYSTEMID");
            stringBuilder.AppendLine(" INNER JOIN T_ORG_ACCTSYSDETAIL acctSubOrg on acctSubOrg.FEntryID=acctOrg.FEntryID");
            stringBuilder.AppendLine(" WHERE {0} ");
            stringBuilder.AppendFormat(" AND acctSys.FACCTSYSTEMID={0} AND acctOrg.FMAINORGID={1})", condition.AcntSystemId, condition.AcntOrgId);
            return stringBuilder.ToString();
        }

        private string GetCurrencyNameById(long currencyId)
        {
            QueryBuilderParemeter val = (QueryBuilderParemeter)(object)new QueryBuilderParemeter();
            val.FormId=("BD_Currency");
            val.SelectItems=(new List<SelectorItemInfo>
            {
                (SelectorItemInfo)(object)new SelectorItemInfo("FName")
            });
            val.FilterClauseWihtKey=("FCURRENCYID =@FCURRENCYID and FLOCALEID=@FLOCALEID ");
            List<SqlParam> list = new List<SqlParam>();
            list.Add((SqlParam)(object)new SqlParam("@FCURRENCYID", KDDbType.Int64, (object)currencyId));
            list.Add((SqlParam)(object)new SqlParam("@FLOCALEID", KDDbType.Int64, (object)((AbstractSysReportServicePlugIn)this).Context.UserLocale.LCID));
            IQueryService service = ServiceHelper.GetService<IQueryService>();
            DynamicObjectCollection dynamicObjectCollection = service.GetDynamicObjectCollection(((AbstractSysReportServicePlugIn)this).Context, val, list);
            if (dynamicObjectCollection == null || ((Collection<DynamicObject>)(object)dynamicObjectCollection).Count == 0)
            {
                return string.Empty;
            }
            return ((Collection<DynamicObject>)(object)dynamicObjectCollection)[0]["FName"].ToString();
        }

        private void ClearParentCustomFilter(IRptParams filter)
        {
            if (filter.FilterParameter.CustomFilter != null && !(filter.FilterParameter.CustomFilter.DynamicObjectType == (DynamicObjectType)null) && filter.FilterParameter.CustomFilter.DynamicObjectType.Properties != null)
            {
                foreach (DynamicProperty item in (ReadOnlyCollection<DynamicProperty>)(object)filter.FilterParameter.CustomFilter.DynamicObjectType.Properties)
                {
                    if (!item.IsReadOnly)
                    {
                        filter.FilterParameter.CustomFilter[item]= (object)null;
                    }
                }
                filter.FilterParameter.FilterString=(string.Empty);
                filter.FilterParameter.FilterRows.Clear();
            }
        }

        protected AbstractCBReportService()
            : base()
        {
        }
    }
}
